package vn.gq.udv.utils;


import vn.gq.udv.db.DatabaseHelper;
import vn.gq.udv.template.GQConst;

import android.content.Context;

public class SQLiteDatabaseVersionHandler {
	
	public static final String DBVERSION_KEY = "dbversion";
	public static final String OLD_DATABASE_PATH;
	
	static {
		OLD_DATABASE_PATH = "/data/data/"+GQConst.PACKAGENAME+"/databases/story";
	}
	
	private Context context;
	private SharePreferenceUtil pref;
	
	public SQLiteDatabaseVersionHandler(Context context) {
		this.context = context;
		pref = new SharePreferenceUtil(context);
	}
	
	public void setDatabaseVersion(int version) {
		pref.putInt(DBVERSION_KEY, version);
	}
	
	public int getDatabaseVersion() {
		return pref.getInt(DBVERSION_KEY, 1);
	}
	
	public void checkDBVersionAndUpgrade() {
		int newVersion = GQConst.DB.DBVERSION;
		int currentVersion = getDatabaseVersion();
		FileHelper fileHelper = FileHelper.getInstance(context);
		if (currentVersion != newVersion) {
			context.deleteDatabase(DatabaseHelper.DBNAME);
			fileHelper.delete(GQConst.DB.DATABASEPATH_SD);
			setDatabaseVersion(newVersion);
		}
		
		if (fileHelper.isExist(OLD_DATABASE_PATH) && !DatabaseHelper.DBNAME.equals("story")) {
			context.deleteDatabase("story");
		}
	}
}
